package com.autoplaza;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Timer;
import java.util.TimerTask;
//import kankan.wheel.R;
import kankan.wheel.widget.OnWheelChangedListener;
import kankan.wheel.widget.OnWheelScrollListener;
import kankan.wheel.widget.WheelView;
import kankan.wheel.widget.adapters.AbstractWheelTextAdapter;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Rect;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.opengl.Visibility;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.webkit.WebView;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ToggleButton;

public class Resultados extends Activity {
	InputStream is = null;
	private String result,issearch;
	String[] modelo,numanuncio,year,marca,transmision,precio,kilometraje,
	color1,color2,lugar,foto,numfoto,version;
	private Resultados_Adapter adapter;
	private ListView list;
	private ProgressDialog progressDialog;
	String substr1,substr2, sb9,content;
	int var=0;
	SharedPreferences pref;
	SharedPreferences.Editor editor;
	int total,flag,offset,numpagina,paginas,ultimapagina;
	Button back, next, regresar, ordenar, refinar, btnmenu;
	Timer tim;
	boolean metodo;
	WebView myWebView;
	// Scrolling flag
	private boolean scrolling = false;
	Dialog dialog;
	ToggleButton ascdes;
	int filtro=1;  //porque es visible desde el elemento cero
	int asc_des=1;
	String consultaInicial;
	int totalcarros=0;
	int booltimer = 0;
	String urlBanner = null;

	@Override
	protected void onResume() {
		super.onResume();
		SharedPreferences preferences= getSharedPreferences("Carro",Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = preferences.edit();
		editor.putString("content", content);
		editor.commit();
	}



	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.resultados);
		
		SharedPreferences sp= getSharedPreferences("Carro",Context.MODE_PRIVATE);
		SharedPreferences.Editor editor2 = sp.edit();
		
		if(sp.getInt("ponersplash", 0) == 1){
			Intent in = new Intent(Resultados.this, SplashPublicidad.class);
			startActivity(in);
		}
		
		editor2.putInt("ponersplash", 10).commit();
		
		btnmenu = (Button) findViewById(R.id.btn_menu);
		btnmenu.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {

				Intent goManuLateral = new Intent(Resultados.this, MenuLateral.class);
				goManuLateral.putExtra("clase","Resultados");
				startActivity(goManuLateral);

			}
		});
		
		
		int size = Utils.getScreenSize2(Resultados.this);
		if( size == 1){
			RelativeLayout lin = (RelativeLayout) findViewById(R.id.linearLayout1);
			lin.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 30));
			RelativeLayout.LayoutParams params0 = new RelativeLayout.LayoutParams(25, 25);
			params0.addRule(RelativeLayout.CENTER_HORIZONTAL);
			params0.addRule(RelativeLayout.CENTER_VERTICAL);
			params0.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
			btnmenu.setLayoutParams(params0);
		}		
		if( size == 2){
			RelativeLayout lin = (RelativeLayout) findViewById(R.id.linearLayout1);
			lin.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 60));	
			RelativeLayout.LayoutParams params0 = new RelativeLayout.LayoutParams(50, 50);
			params0.addRule(RelativeLayout.CENTER_HORIZONTAL);
			params0.addRule(RelativeLayout.CENTER_VERTICAL);
			params0.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
			btnmenu.setLayoutParams(params0);
//			btnmenu.setLayoutParams(new LinearLayout.LayoutParams(45, 45));

		}		
		if( size == 3){
			RelativeLayout lin = (RelativeLayout) findViewById(R.id.linearLayout1);
			lin.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 80));
			RelativeLayout.LayoutParams params0 = new RelativeLayout.LayoutParams(70, 70);
			params0.addRule(RelativeLayout.CENTER_HORIZONTAL);
			params0.addRule(RelativeLayout.CENTER_VERTICAL);
			params0.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
			btnmenu.setLayoutParams(params0);
//			btnmenu.setLayoutParams(new LinearLayout.LayoutParams(80, 80));

		}

		ordenar=(Button) findViewById(R.id.ordenar);
		refinar=(Button) findViewById(R.id.refinarbusqueda);



		myWebView = (WebView)this.findViewById(R.id.webViewResultados);
		myWebView.getSettings().setJavaScriptEnabled(true);
		myWebView.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
		//        myWebView.loadUrl("http://planetaapps.com/apps/tagcorto.html");

		metodo = isNetwork();
		if(metodo==false){
			dialogoInternet();
		}else{

			pref=getSharedPreferences("Carro", MODE_PRIVATE);
			editor=pref.edit();
			back=(Button) findViewById(R.id.back);
			next=(Button) findViewById(R.id.next);
			back.setVisibility(View.INVISIBLE);
			next.setVisibility(View.INVISIBLE);
			Bundle extras=getIntent().getExtras();
			if(extras!=null){
				sb9=extras.getString("sb9");
				content=extras.getString("content");
				//SPLASH
				SharedPreferences preferences= getSharedPreferences("Carro",Context.MODE_PRIVATE);
				issearch=preferences.getString("iscontent", "null");
				if(issearch.equals("true")){
					Log.i("PUBLICIDAD", "CONTENT");
					urlBanner = "http://iphone.autoplaza.com.mx/BannersAndroid/Banners.aspx?marca=&modelo=&busqueda="+content;
					myWebView.loadUrl(urlBanner);
				}else{
					SharedPreferences preferences2= getSharedPreferences("Carro",Context.MODE_PRIVATE);
					String marcasplash=preferences2.getString("marca", "[Cualquiera]");
					String modeloplash=preferences2.getString("modelo", "[Cualquiera]");
					boolean marcabool=marcasplash.equals("[Cualquiera]");
					boolean modelobool=modeloplash.equals("[Cualquiera]");
					if(marcabool == false && modelobool == true){
						urlBanner = "http://iphone.autoplaza.com.mx/BannersAndroid/Banners.aspx?marca="+marcasplash+"&modelo=&busqueda=";
						myWebView.loadUrl(urlBanner);
						Log.i("PUBLICIDAD", "2");

					}
					if(modelobool == false && marcabool == false){
						urlBanner = "http://iphone.autoplaza.com.mx/BannersAndroid/Banners.aspx?marca="+modeloplash+"&modelo=&busqueda=";
						myWebView.loadUrl(urlBanner);
						Log.i("PUBLICIDAD", "3");

					}

				}
				Log.i("url mia", "oncreate sb9 "+sb9);
				//					content = extras.getString("context");
			}

			consulta(sb9);
			cargarInformacion();	//este manda a llamar a onbtener arreglos



			next.setOnClickListener(new OnClickListener() {
				String consulta=null;
				SharedPreferences preferences= getSharedPreferences("Carro",Context.MODE_PRIVATE);

				@Override
				public void onClick(View v) {
					metodo = isNetwork();
					if(metodo==false){
						dialogoInternet();
					}else{

						editor.putInt("offset", offset+10);
						editor.putInt("numpagina", numpagina+1);
						editor.commit();
						int off=pref.getInt("offset", 0);
						Log.i("url mia", "offset "+offset);
						Log.i("url mia", "offsetpref "+off);

						SharedPreferences.Editor editor=preferences.edit();
						Log.i("url mia", "sb9 "+sb9);

						Log.i("url mia", "con "+consultaInicial);


						String offSetUrl=consultaInicial.replace("offset="+offset, "offset="+off);
						//****
						if(preferences.getInt("ascdes", 99) == 1){//1 ascendente
							switch (preferences.getInt("country", 99)) {
							//**
							case 0:
								consulta=offSetUrl.replace(preferences.getString("offsetquery", "&offset"), "&offset");
								editor.putString("offsetquery", "&offset");
								editor.commit();
								Log.i("url mia", preferences.getString("offsetquery", "&offset"));
								break;
							case 1:
								consulta=offSetUrl.replace(preferences.getString("offsetquery", "&offset"), "&orderby=year;asc&offset");
								editor.putString("offsetquery", "&orderby=year;asc&offset");
								editor.commit();
								Log.i("url mia", preferences.getString("offsetquery", "&offset"));

								break;
							case 2:
								consulta=offSetUrl.replace(preferences.getString("offsetquery", "&offset"), "&orderby=precio;asc&offset");
								editor.putString("offsetquery", "&orderby=precio;asc&offset");
								editor.commit();
								Log.i("url mia", preferences.getString("offsetquery", "&offset"));

								break;
							case 3:
								consulta=offSetUrl.replace(preferences.getString("offsetquery", "&offset"), "&orderby=colorexterior;asc&offset");
								editor.putString("offsetquery", "&orderby=colorexterior;asc&offset");
								editor.commit();
								Log.i("url mia", preferences.getString("offsetquery", "&offset"));

								break;
							case 4:
								consulta=offSetUrl.replace(preferences.getString("offsetquery", "&offset"), "&orderby=modelo;asc&offset");
								editor.putString("offsetquery", "&orderby=modelo;asc&offset");
								editor.commit();
								Log.i("url mia", preferences.getString("offsetquery", "&offset"));

								break;
							case 5:
								consulta=offSetUrl.replace(preferences.getString("offsetquery", "&offset"), "&orderby=tipotransmision;asc&offset");
								editor.putString("offsetquery", "&orderby=tipotransmision;asc&offset");
								editor.commit();
								Log.i("url mia", preferences.getString("offsetquery", "&offset"));

								break;
							case 6:
								Log.i("url mia", "offseturl "+offSetUrl);
								Log.i("url mia", "target "+preferences.getString("offsetquery", "&offset"));
								Log.i("url mia", "objective &orderby=kilometraje;asc&offset");

								consulta=offSetUrl.replace(preferences.getString("offsetquery", "&offset"), "&orderby=kilometraje;asc&offset");
								editor.putString("offsetquery", "&orderby=kilometraje;asc&offset");
								editor.commit();
								Log.i("url mia", preferences.getString("offsetquery", "&offset"));

								break;

							default:
								consulta=offSetUrl.replace(preferences.getString("offsetquery", "&offset"), "&offset");
								editor.putString("offsetquery", "&offset");
								editor.commit();
								Log.i("url mia", preferences.getString("offsetquery", "&offset"));


								break;
								//**

								//						case 0:
								//							consulta=offSetUrl.replace("&offset", "&offset");
								//							break;
								//						case 1:
								//							consulta=offSetUrl.replace("&offset", "&orderby=year;asc&offset");
								//							break;
								//						case 2:
								//							consulta=offSetUrl.replace("&offset", "&orderby=precio;asc&offset");
								//							break;
								//						case 3:
								//							consulta=offSetUrl.replace("&offset", "&orderby=colorexterior;asc&offset");
								//							break;
								//						case 4:
								//							consulta=offSetUrl.replace("&offset", "&orderby=modelo;asc&offset");
								//							break;
								//						case 5:
								//							consulta=offSetUrl.replace("&offset", "&orderby=tipotransmision;asc&offset");
								//							break;
								//						case 6:
								//							consulta=offSetUrl.replace("&offset", "&orderby=kilometraje;asc&offset");
								//							break;
								//
								//						default:
								//							consulta=offSetUrl.replace("&offset", "&offset");
								//
								//							break;
							}

						}else if(preferences.getInt("ascdes", 99) == 2){ //2 descendente
							switch (preferences.getInt("country", 99)) {

							//**
							case 0:
								consulta=offSetUrl.replace(preferences.getString("offsetquery", "&offset"), "&offset");
								editor.putString("offsetquery", "&offset");
								editor.commit();
								Log.i("url mia", preferences.getString("offsetquery", "&offset"));


								break;
							case 1:
								consulta=offSetUrl.replace(preferences.getString("offsetquery", "&offset"), "&orderby=year;desc&offset");
								editor.putString("offsetquery", "&orderby=year;desc&offset");
								editor.commit();
								Log.i("url mia", preferences.getString("offsetquery", "&offset"));


								break;
							case 2:
								consulta=offSetUrl.replace(preferences.getString("offsetquery", "&offset"), "&orderby=precio;desc&offset");
								editor.putString("offsetquery", "&orderby=precio;desc&offset");
								editor.commit();
								Log.i("url mia", preferences.getString("offsetquery", "&offset"));


								break;
							case 3:
								consulta=offSetUrl.replace(preferences.getString("offsetquery", "&offset"), "&orderby=colorexterior;desc&offset");
								editor.putString("offsetquery", "&orderby=colorexterior;desc&offset");
								editor.commit();
								Log.i("url mia", preferences.getString("offsetquery", "&offset"));


								break;
							case 4:
								consulta=offSetUrl.replace(preferences.getString("offsetquery", "&offset"), "&orderby=modelo;desc&offset");
								editor.putString("offsetquery", "&orderby=modelo;desc&offset");
								editor.commit();
								Log.i("url mia", preferences.getString("offsetquery", "&offset"));


								break;
							case 5:
								consulta=offSetUrl.replace(preferences.getString("offsetquery", "&offset"), "&orderby=tipotransmision;desc&offset");
								editor.putString("offsetquery", "&orderby=tipotransmision;desc&offset");
								editor.commit();
								Log.i("url mia", preferences.getString("offsetquery", "&offset"));


								break;
							case 6:
								consulta=offSetUrl.replace(preferences.getString("offsetquery", "&offset"), "&orderby=kilometraje;desc&offset");
								editor.putString("offsetquery", "&orderby=kilometraje;desc&offset");
								editor.commit();
								Log.i("url mia", preferences.getString("offsetquery", "&offset"));


								break;

							default:
								consulta=offSetUrl.replace(preferences.getString("offsetquery", "&offset"), "&offset");
								editor.putString("offsetquery", "&offset");
								editor.commit();
								Log.i("url mia", preferences.getString("offsetquery", "&offset"));


								break;
								//**
								//						case 0:
								//							consulta=offSetUrl.replace("&offset", "&offset");
								//							break;
								//						case 1:
								//							consulta=offSetUrl.replace("&offset", "&orderby=year;desc&offset");
								//							break;
								//						case 2:
								//							consulta=offSetUrl.replace("&offset", "&orderby=precio;desc&offset");
								//							break;
								//						case 3:
								//							consulta=offSetUrl.replace("&offset", "&orderby=colorexterior;desc&offset");
								//							break;
								//						case 4:
								//							consulta=offSetUrl.replace("&offset", "&orderby=modelo;desc&offset");
								//							break;
								//						case 5:
								//							consulta=offSetUrl.replace("&offset", "&orderby=tipotransmision;desc&offset");
								//							break;
								//						case 6:
								//							consulta=offSetUrl.replace("&offset", "&orderby=kilometraje;desc&offset");
								//							break;
								//
								//						default:
								//							consulta=offSetUrl.replace("&offset", "&offset");
								//							break;
							}
							editor.commit();
						}else{
							consulta=offSetUrl;
						}

						//****

						Log.i("url mia", "final next "+consulta);
						Intent next=new Intent(Resultados.this, Resultados.class);
						next.putExtra("sb9", consulta);
						startActivity(next);

					}
				}
			});
			back.setOnClickListener(new OnClickListener() {
				String consulta=null;
				SharedPreferences preferences= getSharedPreferences("Carro",Context.MODE_PRIVATE);
				@Override
				public void onClick(View v) {
					metodo = isNetwork();
					if(metodo==false){
						dialogoInternet();
					}else{
						editor.putInt("offset", offset-10);
						editor.putInt("numpagina", numpagina-1);
						editor.commit();
						int off=pref.getInt("offset", 0);
						Log.i("url mia", "offset "+offset);
						Log.i("url mia", "offsetpref "+off);

						SharedPreferences.Editor editor=preferences.edit();

						String offSetUrl=sb9.replace("offset="+offset, "offset="+off);

						//****
						if(preferences.getInt("ascdes", 99) == 1){//1 ascendente
							switch (preferences.getInt("country", 99)) {
							//**
							case 0:
								consulta=offSetUrl.replace(preferences.getString("offsetquery", "&offset"), "&offset");
								editor.putString("offsetquery", "&offset");
								editor.commit();
								Log.i("url mia", preferences.getString("offsetquery", "&offset"));
								break;
							case 1:
								consulta=offSetUrl.replace(preferences.getString("offsetquery", "&offset"), "&orderby=year;asc&offset");
								editor.putString("offsetquery", "&orderby=year;asc&offset");
								editor.commit();
								Log.i("url mia", preferences.getString("offsetquery", "&offset"));

								break;
							case 2:
								consulta=offSetUrl.replace(preferences.getString("offsetquery", "&offset"), "&orderby=precio;asc&offset");
								editor.putString("offsetquery", "&orderby=precio;asc&offset");
								editor.commit();
								Log.i("url mia", preferences.getString("offsetquery", "&offset"));

								break;
							case 3:
								consulta=offSetUrl.replace(preferences.getString("offsetquery", "&offset"), "&orderby=colorexterior;asc&offset");
								editor.putString("offsetquery", "&orderby=colorexterior;asc&offset");
								editor.commit();
								Log.i("url mia", preferences.getString("offsetquery", "&offset"));

								break;
							case 4:
								consulta=offSetUrl.replace(preferences.getString("offsetquery", "&offset"), "&orderby=modelo;asc&offset");
								editor.putString("offsetquery", "&orderby=modelo;asc&offset");
								editor.commit();
								Log.i("url mia", preferences.getString("offsetquery", "&offset"));

								break;
							case 5:
								consulta=offSetUrl.replace(preferences.getString("offsetquery", "&offset"), "&orderby=tipotransmision;asc&offset");
								editor.putString("offsetquery", "&orderby=tipotransmision;asc&offset");
								editor.commit();
								Log.i("url mia", preferences.getString("offsetquery", "&offset"));

								break;
							case 6:
								consulta=offSetUrl.replace(preferences.getString("offsetquery", "&offset"), "&orderby=kilometraje;asc&offset");
								editor.putString("offsetquery", "&orderby=kilometraje;asc&offset");
								editor.commit();
								Log.i("url mia", preferences.getString("offsetquery", "&offset"));

								break;

							default:
								consulta=offSetUrl.replace(preferences.getString("offsetquery", "&offset"), "&offset");
								editor.putString("offsetquery", "&offset");
								editor.commit();
								Log.i("url mia", preferences.getString("offsetquery", "&offset"));


								break;
								//**

								//						case 0:
								//							consulta=offSetUrl.replace("&offset", "&offset");
								//							break;
								//						case 1:
								//							consulta=offSetUrl.replace("&offset", "&orderby=year;asc&offset");
								//							break;
								//						case 2:
								//							consulta=offSetUrl.replace("&offset", "&orderby=precio;asc&offset");
								//							break;
								//						case 3:
								//							consulta=offSetUrl.replace("&offset", "&orderby=colorexterior;asc&offset");
								//							break;
								//						case 4:
								//							consulta=offSetUrl.replace("&offset", "&orderby=modelo;asc&offset");
								//							break;
								//						case 5:
								//							consulta=offSetUrl.replace("&offset", "&orderby=tipotransmision;asc&offset");
								//							break;
								//						case 6:
								//							consulta=offSetUrl.replace("&offset", "&orderby=kilometraje;asc&offset");
								//							break;
								//
								//						default:
								//							consulta=offSetUrl.replace("&offset", "&offset");
								//
								//							break;
							}
							//						editor.commit();
						}else if(preferences.getInt("ascdes", 99) == 2){ //2 descendente
							switch (preferences.getInt("country", 99)) {

							//**
							case 0:
								consulta=offSetUrl.replace(preferences.getString("offsetquery", "&offset"), "&offset");
								editor.putString("offsetquery", "&offset");
								editor.commit();
								Log.i("url mia", preferences.getString("offsetquery", "&offset"));


								break;
							case 1:
								consulta=offSetUrl.replace(preferences.getString("offsetquery", "&offset"), "&orderby=year;desc&offset");
								editor.putString("offsetquery", "&orderby=year;desc&offset");
								editor.commit();
								Log.i("url mia", preferences.getString("offsetquery", "&offset"));


								break;
							case 2:
								consulta=offSetUrl.replace(preferences.getString("offsetquery", "&offset"), "&orderby=precio;desc&offset");
								editor.putString("offsetquery", "&orderby=precio;desc&offset");
								Log.i("url mia", preferences.getString("offsetquery", "&offset"));


								break;
							case 3:
								consulta=offSetUrl.replace(preferences.getString("offsetquery", "&offset"), "&orderby=colorexterior;desc&offset");
								editor.putString("offsetquery", "&orderby=colorexterior;desc&offset");
								editor.commit();
								Log.i("url mia", preferences.getString("offsetquery", "&offset"));


								break;
							case 4:
								consulta=offSetUrl.replace(preferences.getString("offsetquery", "&offset"), "&orderby=modelo;desc&offset");
								editor.putString("offsetquery", "&orderby=modelo;desc&offset");
								editor.commit();
								Log.i("url mia", preferences.getString("offsetquery", "&offset"));


								break;
							case 5:
								consulta=offSetUrl.replace(preferences.getString("offsetquery", "&offset"), "&orderby=tipotransmision;desc&offset");
								editor.putString("offsetquery", "&orderby=tipotransmision;desc&offset");
								editor.commit();
								Log.i("url mia", preferences.getString("offsetquery", "&offset"));


								break;
							case 6:
								consulta=offSetUrl.replace(preferences.getString("offsetquery", "&offset"), "&orderby=kilometraje;desc&offset");
								editor.putString("offsetquery", "&orderby=kilometraje;desc&offset");
								editor.commit();
								Log.i("url mia", preferences.getString("offsetquery", "&offset"));


								break;

							default:
								consulta=offSetUrl.replace(preferences.getString("offsetquery", "&offset"), "&offset");
								editor.putString("offsetquery", "&offset");
								editor.commit();
								Log.i("url mia", preferences.getString("offsetquery", "&offset"));


								break;
								//**
								//						case 0:
								//							consulta=offSetUrl.replace("&offset", "&offset");
								//							break;
								//						case 1:
								//							consulta=offSetUrl.replace("&offset", "&orderby=year;desc&offset");
								//							break;
								//						case 2:
								//							consulta=offSetUrl.replace("&offset", "&orderby=precio;desc&offset");
								//							break;
								//						case 3:
								//							consulta=offSetUrl.replace("&offset", "&orderby=colorexterior;desc&offset");
								//							break;
								//						case 4:
								//							consulta=offSetUrl.replace("&offset", "&orderby=modelo;desc&offset");
								//							break;
								//						case 5:
								//							consulta=offSetUrl.replace("&offset", "&orderby=tipotransmision;desc&offset");
								//							break;
								//						case 6:
								//							consulta=offSetUrl.replace("&offset", "&orderby=kilometraje;desc&offset");
								//							break;
								//
								//						default:
								//							consulta=offSetUrl.replace("&offset", "&offset");
								//							break;
							}
							//						editor.commit();
						}else{
							consulta=offSetUrl;
						}

						//****


						//****


						Log.i("url mia", consulta);
						Intent next=new Intent(Resultados.this, Resultados.class);
						next.putExtra("sb9", consulta);
						startActivity(next);
					}
				}
			});

		}

		ordenar.setOnClickListener(new OnClickListener() {
			int var=0;
			//mayor relevancia, año, precio, color, modelo, transmision, kilometraje
			@Override
			public void onClick(View arg0) {
				asc_des = 1;
				filtro = 1;
				dialog = new Dialog(Resultados.this);
				dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
				// retrieve display dimensions
				Rect displayRectangle = new Rect();
				Window window = Resultados.this.getWindow();
				window.getDecorView().getWindowVisibleDisplayFrame(displayRectangle);

				// inflate and adjust layout
				LayoutInflater inflater = (LayoutInflater)Resultados.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				View layout = inflater.inflate(R.layout.dialog_ordenar, null);
				layout.setMinimumWidth((int)(displayRectangle.width() * 0.9f));
				//				layout.setMinimumHeight((int)(displayRectangle.height() * 0.9f));

				dialog.setContentView(layout);

				Button cancel = (Button) layout.findViewById(R.id.cancelard);
				Button aceptar = (Button) layout.findViewById(R.id.aceptard);
				ascdes = (ToggleButton) layout.findViewById(R.id.toggle);

				cancel.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						dialog.dismiss();
						dialog.cancel();
					}
				});

				ascdes.setOnCheckedChangeListener(new OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
						if(isChecked){
							asc_des=2;
							Log.i("ischecked", "ischecked");
							//							Toast.makeText(getApplicationContext(), "ascdes "+asc_des, Toast.LENGTH_LONG).show();
						}else{
							asc_des=1;
							Log.i("isnotchecked", "isnotchecked");
							//							Toast.makeText(getApplicationContext(), "ascdes "+asc_des, Toast.LENGTH_LONG).show();


						}
						//						if(var%2==1){
						//							asc_des=1;
						//							ascdes.setText("ascendente");
						//						}else{
						//							asc_des=2;
						//							ascdes.setText("descendente");
						//						}
						//						var++;
					}

				});

				final WheelView country = (WheelView) dialog.findViewById(R.id.country);
				country.setVisibleItems(3);
				country.setViewAdapter(new CountryAdapter(Resultados.this));

				country.addChangingListener(new OnWheelChangedListener() {
					public void onChanged(WheelView wheel, int oldValue, int newValue) {
						if (!scrolling) {
							//					    	filtro = country.getCurrentItem();
						}
					}
				});

				country.addScrollingListener( new OnWheelScrollListener() {
					public void onScrollingStarted(WheelView wheel) {
						scrolling = true;
					}
					public void onScrollingFinished(WheelView wheel) {
						scrolling = false;
						filtro=country.getCurrentItem();
						Log.i("Filtro",	""+filtro);
					}

				});

				country.setCurrentItem(1);

				aceptar.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						dialog.dismiss();
						pref=getSharedPreferences("Carro", MODE_PRIVATE);
						agregarPreferencia(filtro);
						agregarascdes(asc_des);
						Log.i("sb9 click aceptar", sb9);
						String consulta = sb9.replace("offset="+pref.getInt("offset", 0), "offset=0");
						Log.i("url mia", "sb9 aceptar "+consulta);
						Intent intent=new Intent(Resultados.this, Resultados.class);
						intent.putExtra("sb9", consulta);


						editor.putInt("flag", 0);
						editor.putInt("pref", 0);
						editor.putInt("numpagina", 0);
						editor.putInt("offset", 0);


						editor.commit();
						startActivity(intent);




					}
				});



				//				ascdes.setOnClickListener(new OnClickListener() {
				//					
				//					@Override
				//					public void onClick(View v) {
				//						if(ascdes.isChecked()){
				//							asc_des=2;
				////							Toast.makeText(getApplicationContext(), "ascdes "+asc_des, Toast.LENGTH_LONG).show();
				//						}else{
				//							asc_des=1;
				////							Toast.makeText(getApplicationContext(), "ascdes "+asc_des, Toast.LENGTH_LONG).show();
				//
				//
				//						}
				////						if(var%2==1){
				////							asc_des=1;
				////							ascdes.setText("ascendente");
				////						}else{
				////							asc_des=2;
				////							ascdes.setText("descendente");
				////						}
				////						var++;
				//					}
				//
				//	
				//				});





				dialog.show();

			}
		});

		refinar.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent goRefinar = new Intent(Resultados.this, RefinarBusqueda.class);
				goRefinar.putExtra("sb9", sb9);
				startActivity(goRefinar);


			}
		});


	}





	private void agregarascdes(int i) {
		SharedPreferences preferences= getSharedPreferences("Carro",Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = preferences.edit();
		editor.putInt("ascdes", i);
		editor.commit();				
	}

	private void agregarPreferencia(int country) {
		SharedPreferences preferences= getSharedPreferences("Carro",Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = preferences.edit();
		editor.putInt("country", country);
		editor.commit();		
	}

	/**
	 * Adapter for countries
	 */
	private class CountryAdapter extends AbstractWheelTextAdapter {
		private String countries[] =
				new String[] {"Mayor Relevancia","Año", "Precio", "Color","Modelo", "Transmisión", "Kilometraje"};

		/**
		 * Constructor
		 */
		protected CountryAdapter(Context context) {
			super(context, R.layout.country_layout, NO_RESOURCE);

			setItemTextResource(R.id.country_name);
		}

		@Override
		public View getItem(int index, View cachedView, ViewGroup parent) {
			View view = super.getItem(index, cachedView, parent);
			return view;
		}

		@Override
		public int getItemsCount() {
			return countries.length;
		}

		@Override
		protected CharSequence getItemText(int index) {
			return countries[index];
		}
	}

	private void obtenerArreglos() {
		String[] arrayGeneral=result.trim().split("%%%");
		Log.i("result", ""+result);
		String[] arrayNoResul=arrayGeneral[0].trim().split("@@@");
		Log.i("NUMERO CARROS", arrayNoResul[1]);
		totalcarros = Integer.parseInt(arrayNoResul[1]);

		//		SharedPreferences preferences3= getSharedPreferences("Carro",Context.MODE_PRIVATE);

		//		String marca2= preferences3.getString("marca", "");
		//		TextView estasviendo = (TextView) findViewById(R.id.estasviendo);
		//		estasviendo.setText("Estas viendo: \""+marca2+"\"   ");
		//        SharedPreferences preferences2= getSharedPreferences("mipref",Context.MODE_PRIVATE);
		//
		//		int rango = preferences2.getInt("offset", 0);
		//		int rango1 = rango+1;
		//		int rango2 = rango+10;
		//		
		//		TextView txtrango = (TextView) findViewById(R.id.rango);
		//		txtrango.setText(rango1+" a "+rango2+" ( Total: "+totalcarros+" )");


		Log.i("TAM ELEMENTO CERO", "TAM "+arrayNoResul.length);
		flag=pref.getInt("flag", 0);
		offset=pref.getInt("offset", 0);
		//************Necesito reiniciar flag a cero para otra búsqueda********/////////
		if(flag==0){
			flag=1;
			total=Integer.parseInt(arrayNoResul[1]);
			paginas=(int)total/10;			//numero de paginas
			ultimapagina=total%10;		//ultima pagina
			Log.i("FLAG",	 "FLAG VALE 0");
			editor.putInt("total", total);
			editor.putInt("paginas", paginas);
			editor.putInt("ultimapagina", ultimapagina);
			editor.putInt("flag", flag);
			editor.commit();
		}

		editor.putInt("offset", offset);
		editor.commit();
		ultimapagina=pref.getInt("ultimapagina", 0);
		numpagina=pref.getInt("numpagina", 0);
		Log.i("NUM PAGINA INICIAL", "PAGINA "+numpagina);
		paginas=pref.getInt("paginas", 0);

		if(arrayNoResul[1].equals("0")){
			Log.i("TAM NO RESUL", "NO RESULTADOS ");
			var=1;
		}else if((paginas==0)  &&  (ultimapagina!=0)){
			Log.i("ULTIMA PAGINA", ""+ultimapagina);
			modelo=new String[ultimapagina];
			numanuncio=new String[ultimapagina];
			year=new String[ultimapagina];
			marca=new String[ultimapagina];
			transmision=new String[ultimapagina];
			precio=new String[ultimapagina];
			kilometraje=new String[ultimapagina];
			color1=new String[ultimapagina];
			color2=new String[ultimapagina];
			lugar=new String[ultimapagina];
			foto=new String[ultimapagina];
			numfoto=new String[ultimapagina];
			version=new String[ultimapagina];

			for(int i=0;i<modelo.length;i++){
				//	    	   if(i<(modelo.length-1)){
				String[] helper=arrayGeneral[i+1].trim().split("@@@");
				Log.i("ARRAY GENERAL", "TAM "+helper.length);

				modelo[i]=helper[0];
				numanuncio[i]=helper[1];
				year[i]=helper[2];
				marca[i]=helper[3];
				transmision[i]=helper[4];
				precio[i]=helper[5];
				kilometraje[i]=helper[6];
				color1[i]=helper[7];
				color2[i]=helper[8];
				lugar[i]=helper[9];

				if(helper[10].equals("null")){
					foto[i]="nofoto";
				}else{
					String st=helper[10].replaceAll(" ", "%20");
					foto[i]=st;
				}

				numfoto[i]=helper[11];
				version[i]=helper[12];


				//	    	   }

			}

			for(int i=0; i<modelo.length; i++){
				Log.i("MODELO"+modelo.length, ""+modelo[i]);
				Log.i("NUMANUNCIO"+numanuncio.length, ""+numanuncio[i]);
				Log.i("AÑO"+year.length, ""+year[i]);
				Log.i("MARCA"+marca.length, ""+marca[i]);
				Log.i("TRANSMISION"+transmision.length, ""+transmision[i]);
				Log.i("PRECIO"+precio.length, ""+precio[i]);
				Log.i("KILOMETRAJE"+kilometraje.length, ""+kilometraje[i]);
				Log.i("COLOR1"+color1.length, ""+color1[i]);
				Log.i("COLOR2"+color2.length, ""+color2[i]);
				Log.i("LUGAR"+lugar.length, ""+lugar[i]);
				Log.i("FOTO"+foto.length, ""+foto[i]);
				Log.i("NUMFOTOS"+numfoto.length, ""+numfoto[i]);
				Log.i("VERSION"+version.length, ""+version[i]);
			}	
		}else if(numpagina< paginas && paginas!=0){		//ESTE ES UN CAMBIO
			mostrarNext();
			if(numpagina > 0){
				mostrarBack();
			}
			//        	if(numpagina == 0){
			//        		ocultarBack();
			//        	}
			//Es -1 ya que el primer elemento es el total de autos encontrados en la busqueda, falta manejar que no haya elementos de la busqueda
			modelo=new String[10];
			numanuncio=new String[10];
			year=new String[10];
			marca=new String[10];
			transmision=new String[10];
			precio=new String[10];
			kilometraje=new String[10];
			color1=new String[10];
			color2=new String[10];
			lugar=new String[10];
			foto=new String[10];
			numfoto=new String[10];
			version=new String[10];

			for(int i=0;i<modelo.length;i++){//9

				String[] helper=arrayGeneral[i+1].trim().split("@@@");
				Log.i("ARRAY GENERAL", "TAM "+helper.length);

				modelo[i]=helper[0];
				numanuncio[i]=helper[1];
				year[i]=helper[2];
				marca[i]=helper[3];
				transmision[i]=helper[4];
				precio[i]=helper[5];
				kilometraje[i]=helper[6];
				color1[i]=helper[7];
				color2[i]=helper[8];
				lugar[i]=helper[9];

				if(helper[10].equals("null")){
					foto[i]="nofoto";
				}else{
					String st=helper[10].replaceAll(" ", "%20");
					foto[i]=st;
				}
				numfoto[i]=helper[11];
				version[i]=helper[12];
			}

			for(int i=0; i<modelo.length; i++){
				Log.i("MODELO"+modelo.length, ""+modelo[i]);
				Log.i("NUMANUNCIO"+numanuncio.length, ""+numanuncio[i]);
				Log.i("AÑO"+year.length, ""+year[i]);
				Log.i("MARCA"+marca.length, ""+marca[i]);
				Log.i("TRANSMISION"+transmision.length, ""+transmision[i]);
				Log.i("PRECIO"+precio.length, ""+precio[i]);
				Log.i("KILOMETRAJE"+kilometraje.length, ""+kilometraje[i]);
				Log.i("COLOR1"+color1.length, ""+color1[i]);
				Log.i("COLOR2"+color2.length, ""+color2[i]);
				Log.i("LUGAR"+lugar.length, ""+lugar[i]);
				Log.i("FOTO"+foto.length, ""+foto[i]);
				Log.i("NUMFOTOS"+numfoto.length, ""+numfoto[i]);
				Log.i("VERSION"+version.length, ""+version[i]);
			}		
		}else if(numpagina == paginas){
			mostrarBack();
			//Es -1 ya que el primer elemento es el total de autos encontrados en la busqueda, falta manejar que no haya elementos de la busqueda
			modelo=new String[ultimapagina];
			numanuncio=new String[ultimapagina];
			year=new String[ultimapagina];
			marca=new String[ultimapagina];
			transmision=new String[ultimapagina];
			precio=new String[ultimapagina];
			kilometraje=new String[ultimapagina];
			color1=new String[ultimapagina];
			color2=new String[ultimapagina];
			lugar=new String[ultimapagina];
			foto=new String[ultimapagina];
			numfoto=new String[ultimapagina];
			version=new String[ultimapagina];

			for(int i=0;i<modelo.length;i++){
				String[] helper=arrayGeneral[i+1].split("@@@");
				Log.i("ARRAY GENERAL", "TAM "+helper.length);

				modelo[i]=helper[0];
				numanuncio[i]=helper[1];
				year[i]=helper[2];
				marca[i]=helper[3];
				transmision[i]=helper[4];
				precio[i]=helper[5];
				kilometraje[i]=helper[6];
				color1[i]=helper[7];
				color2[i]=helper[8];
				lugar[i]=helper[9];

				if(helper[10].equals("null")){
					foto[i]="nofoto";
				}else{
					String st=helper[10].replaceAll(" ", "%20");
					foto[i]=st;
				}
				numfoto[i]=helper[11];
				version[i]=helper[12];
			}

			for(int i=0; i<modelo.length; i++){
				Log.i("MODELO"+modelo.length, ""+modelo[i]);
				Log.i("NUMANUNCIO"+numanuncio.length, ""+numanuncio[i]);
				Log.i("AÑO"+year.length, ""+year[i]);
				Log.i("MARCA"+marca.length, ""+marca[i]);
				Log.i("TRANSMISION"+transmision.length, ""+transmision[i]);
				Log.i("PRECIO"+precio.length, ""+precio[i]);
				Log.i("KILOMETRAJE"+kilometraje.length, ""+kilometraje[i]);
				Log.i("COLOR1"+color1.length, ""+color1[i]);
				Log.i("COLOR2"+color2.length, ""+color2[i]);
				Log.i("LUGAR"+lugar.length, ""+lugar[i]);
				Log.i("FOTO"+foto.length, ""+foto[i]);
				Log.i("NUMFOTOS"+numfoto.length, ""+numfoto[i]);
				Log.i("VERSION"+version.length, ""+version[i]);
			}

		}else{
			Log.i("TERMINO", "RESULTADO");
		}
	}


	private void mostrarNext() {
		Resultados.this.runOnUiThread(new Runnable() {
			public void run() {
				next.setVisibility(View.VISIBLE);
			}
		});

	}
	private void mostrarBack() {
		Resultados.this.runOnUiThread(new Runnable() {
			public void run() {
				back.setVisibility(View.VISIBLE);
			}
		});

	}

	private void ocultarBack() {
		Resultados.this.runOnUiThread(new Runnable() {
			public void run() {
				back.setVisibility(View.INVISIBLE);
			}
		});

	}

	private void cargarInformacion() {
		new AsyncActividades().execute("actividades");
	}

	private class AsyncActividades extends AsyncTask<String, Void, Integer> {
		protected void onPostExecute(Integer in) {
			if(var==1){
				progressDialog.dismiss();
				medotoDialog();
			}
			else{
				booltimer=9;
				SharedPreferences preferences3= getSharedPreferences("Carro",Context.MODE_PRIVATE);

				String marca2= preferences3.getString("marca", "[Cualquiera]");
				String modelo2= preferences3.getString("modelo", "[Cualquiera]");
				String year2= preferences3.getString("ano", "[Cualquiera]");
				String ubicacion2= preferences3.getString("ubicacion", "[Cualquiera]");
				String precio2= preferences3.getString("precio", "[Cualquiera]");
				String content= preferences3.getString("content", "Ejemplo : Jetta Rojo 2005");


				StringBuilder sb = new StringBuilder();
				if(!marca2.equals("[Cualquiera]")){
					sb.append("\"");
					sb.append(marca2);
					sb.append("\" ");
				}
				if(!modelo2.equals("[Cualquiera]")){
					sb.append("\"");
					sb.append(modelo2);
					sb.append("\" ");
				}
				if(!year2.equals("[Cualquiera]")){
					sb.append("\"");
					sb.append(year2);
					sb.append("\" ");

				}
				if(!ubicacion2.equals("[Cualquiera]")){
					sb.append("\"");
					sb.append(ubicacion2);
					sb.append("\" ");
				}
				if(!precio2.equals("[Cualquiera]")){
					sb.append("\"");
					sb.append(precio2);
					sb.append("\" ");

				}
				if(!content.equals("Ejemplo : Jetta Rojo 2005")){
					sb.append("\"");
					sb.append(content);
					sb.append("\" ");

				}




				TextView estasviendo = (TextView) findViewById(R.id.estasviendo);
				estasviendo.setText("Estas viendo: "+sb.toString()+"   ");

				SharedPreferences preferences2= getSharedPreferences("Carro",Context.MODE_PRIVATE);

				int rango = preferences2.getInt("offset", 0);
				int rango1 = rango+1;
				int rango2 = rango+10;

				TextView txtrango = (TextView) findViewById(R.id.rango);
				txtrango.setText(rango1+" a "+rango2+" ( Total: "+totalcarros+" )");
				TextView txtpage = (TextView) findViewById(R.id.txtpagenum);
				txtpage.setText("pág. "+(numpagina+1));


				list = (ListView) findViewById(R.id.list);
				adapter=new Resultados_Adapter(Resultados.this, marca, modelo, year, version, transmision, kilometraje, 
						precio, lugar, foto,numfoto, numanuncio, color1, color2, urlBanner);
				list.setAdapter(adapter);
				list.setTextFilterEnabled(true);
				tim=new Timer();
				tim.schedule(new TimerTask() {
					@Override
					public void run() {
						Resultados.this.runOnUiThread(new Runnable() {
							public void run() {
								adapter.notifyDataSetChanged();
							}
						});
					}
				}, 0, 2000);

				//				list.setOnItemClickListener(new OnItemClickListener() {
				//					public void onItemClick(AdapterView<?> parent, View view,
				//							int position, long id) {
				//						
				//							if(isNetwork()){
				//						
				//								Intent in = new Intent(Resultados.this, DetalleaUTO.class);
				//								in.putExtra("modelo",""+modelo[position]);
				//								in.putExtra("numanuncio",""+numanuncio[position]);
				////								in.putExtra("anio",""+year[position]);
				////								in.putExtra("marca",""+marca[position]);
				////								in.putExtra("transmision",""+transmision[position]);
				//								in.putExtra("precio",""+precio[position]);
				////								in.putExtra("kilometraje",""+kilometraje[position]);
				////								in.putExtra("color1",""+color1[position]);
				////								in.putExtra("color2",""+color2[position]);
				////								in.putExtra("lugar",""+lugar[position]);
				//								in.putExtra("foto",""+foto[position]);
				//								in.putExtra("numfoto",""+numfoto[position]);
				//								in.putExtra("version",""+version[position]);
				//								Log.i("FOTO_MANDADA", ""+foto);
				//								startActivity(in);
				//							}else{
				//								dialogoInternet();
				//								
				//							}
				//
				//					}
				//
				//
				//				});
				progressDialog.dismiss();
			}
		}

		protected void onPreExecute() {
			progressDialog = ProgressDialog.show(Resultados.this, "",
					"Buscando...");	}
		protected Integer doInBackground(String... urls) {
			//Calculo de los arreglos en segundo plano
			obtenerArreglos();
			return null;
		}
	}

	private void dialogoInternet() {
		AlertDialog.Builder builder = new AlertDialog.Builder(Resultados.this);
		builder.setMessage("Necesita conexión a Internet")
		.setCancelable(false)
		.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
			}
		});
		AlertDialog alertDialog = builder.create();
		alertDialog.show();		

	}

	public void onBackPressed() {
		SharedPreferences preferences= getSharedPreferences("Carro",Context.MODE_PRIVATE);
		SharedPreferences.Editor editor2 = preferences.edit();
		editor2.putInt("ascdes", 99);
		editor2.putInt("country", 99);
		editor2.putString("offsetquery", "&offset");

		editor2.commit();	

		if(booltimer == 9){
			tim.cancel();
			tim.purge();
		}

//		Intent volver=new Intent(Resultados.this, Buscar.class);
		//Regresar flag a cero para poder capturar de nuevo total,paginas y ultimapagina, necesarias para paginación
		editor.putInt("flag", 0);
		editor.putInt("pref", 0);
		editor.putInt("numpagina", 0);
		editor.putInt("offset", 0);



		editor.commit();
		finish();
//		startActivity(volver);
	}

	public void medotoDialog() {
		final Dialog dialog = new Dialog(Resultados.this);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.rowcustom3);
		Button btn = (Button) dialog.findViewById(R.id.cancel);
		btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.cancel();
				onBackPressed();
				var=0;
			}
		});
		dialog.show();		
	}

	//*****************FALTA PARAR EL TIMER DE REFRRESH

	public void consulta(String sb92) {
		//		consultaInicial;
		InputStream is = null;

		String url=sb92;

		//ME REEMPLAZA EL OFFSET POR OFFSET NUEVAMENTE

		//filtro
		SharedPreferences preferences= getSharedPreferences("Carro",Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = preferences.edit();

		Log.i("TAG FILTRO COUTRY", ""+preferences.getInt("country", 99));
		Log.i("TAG FILTRO ASCDES", ""+preferences.getInt("ascdes", 99));
		if(preferences.getInt("ascdes", 99) == 1){//1 ascendente
			Log.i("url mia", "ascendente");

			switch (preferences.getInt("country", 99)) {
			case 0:
				Log.i("VERIFICACION", "URL "+url+" replace this "+preferences.getString("offsetquery", "&offset")+" for this &offset");
				consultaInicial=url.replace(preferences.getString("offsetquery", "&offset"), "&offset");
				editor.putString("offsetquery", "&offset");
				editor.commit();
				Log.i("url mia", preferences.getString("offsetquery", "&offset"));
				Log.i("url mia", "url url "+consultaInicial);
				sb9 = consultaInicial;

				break;
			case 1:
				Log.i("VERIFICACION", "URL "+url+" replace this "+preferences.getString("offsetquery", "&offset")+" for this &orderby=year;asc&offset");
				consultaInicial=url.replace(preferences.getString("offsetquery", "&offset"), "&orderby=year;asc&offset");
				editor.putString("offsetquery", "&orderby=year;asc&offset");
				editor.commit();
				Log.i("url mia", preferences.getString("offsetquery", "&offset"));
				Log.i("url mia", "url url "+consultaInicial);
				sb9 = consultaInicial;


				break;
			case 2:
				Log.i("VERIFICACION", "URL "+url+" replace this "+preferences.getString("offsetquery", "&offset")+" for this &orderby=precio;asc&offset");
				consultaInicial=url.replace(preferences.getString("offsetquery", "&offset"), "&orderby=precio;asc&offset");
				editor.putString("offsetquery", "&orderby=precio;asc&offset");
				editor.commit();
				Log.i("url mia", preferences.getString("offsetquery", "&offset"));
				Log.i("url mia", "url url "+consultaInicial);
				sb9 = consultaInicial;


				break;
			case 3:
				Log.i("VERIFICACION", "URL "+url+" replace this "+preferences.getString("offsetquery", "&offset")+" for this &orderby=colorexterior;asc&offset");
				consultaInicial=url.replace(preferences.getString("offsetquery", "&offset"), "&orderby=colorexterior;asc&offset");
				editor.putString("offsetquery", "&orderby=colorexterior;asc&offset");
				editor.commit();
				Log.i("url mia", preferences.getString("offsetquery", "&offset"));
				Log.i("url mia", "url url "+consultaInicial);
				sb9 = consultaInicial;


				break;
			case 4:
				Log.i("VERIFICACION", "URL "+url+" replace this "+preferences.getString("offsetquery", "&offset")+" for this &orderby=modelo;asc&offset");
				consultaInicial=url.replace(preferences.getString("offsetquery", "&offset"), "&orderby=modelo;asc&offset");
				editor.putString("offsetquery", "&orderby=modelo;asc&offset");
				editor.commit();
				Log.i("url mia", preferences.getString("offsetquery", "&offset"));
				Log.i("url mia", "url url "+consultaInicial);
				sb9 = consultaInicial;


				break;
			case 5:
				Log.i("VERIFICACION", "URL "+url+" replace this "+preferences.getString("offsetquery", "&offset")+" for this &orderby=tipotransmision;asc&offset");
				consultaInicial=url.replace(preferences.getString("offsetquery", "&offset"), "&orderby=tipotransmision;asc&offset");
				editor.putString("offsetquery", "&orderby=tipotransmision;asc&offset");
				editor.commit();
				Log.i("url mia", preferences.getString("offsetquery", "&offset"));
				Log.i("url mia", "url url "+consultaInicial);
				sb9 = consultaInicial;


				break;
			case 6:
				Log.i("VERIFICACION", "URL "+url+" replace this "+preferences.getString("offsetquery", "&offset")+" for this &orderby=kilometraje;asc&offset");
				consultaInicial=url.replace(preferences.getString("offsetquery", "&offset"), "&orderby=kilometraje;asc&offset");
				editor.putString("offsetquery", "&orderby=kilometraje;asc&offset");
				editor.commit();
				Log.i("url mia", preferences.getString("offsetquery", "&offset"));
				Log.i("url mia", "url url "+consultaInicial);
				sb9 = consultaInicial;


				break;

			default:
				Log.i("VERIFICACION", "URL "+url+" replace this "+preferences.getString("offsetquery", "&offset")+" for this &offset");
				consultaInicial=url.replace(preferences.getString("offsetquery", "&offset"), "&offset");
				editor.putString("offsetquery", "&offset");
				editor.commit();
				Log.i("url mia", preferences.getString("offsetquery", "&offset"));
				Log.i("url mia", "url url "+consultaInicial);
				sb9 = consultaInicial;



				break;
			}
			editor.commit();
		}else if(preferences.getInt("ascdes", 99) == 2){ //2 descendente
			Log.i("url mia", "descendente");

			switch (preferences.getInt("country", 99)) {
			case 0:
				Log.i("VERIFICACION", "URL "+url+" replace this "+preferences.getString("offsetquery", "&offset")+" for this &offset");
				consultaInicial=url.replace(preferences.getString("offsetquery", "&offset"), "&offset");
				editor.putString("offsetquery", "&offset");
				editor.commit();
				Log.i("url mia", preferences.getString("offsetquery", "&offset"));
				Log.i("url mia", "url url "+consultaInicial);
				sb9 = consultaInicial;



				break;
			case 1:
				Log.i("VERIFICACION", "URL "+url+" replace this "+preferences.getString("offsetquery", "&offset")+" for this &orderby=year;asc&offset");
				consultaInicial=url.replace(preferences.getString("offsetquery", "&offset"), "&orderby=year;desc&offset");
				editor.putString("offsetquery", "&orderby=year;desc&offset");
				editor.commit();
				Log.i("url mia", preferences.getString("offsetquery", "&offset"));
				Log.i("url mia", "url url "+consultaInicial);
				sb9 = consultaInicial;



				break;
			case 2:
				Log.i("VERIFICACION", "URL "+url+" replace this "+preferences.getString("offsetquery", "&offset")+" for this &orderby=precio;asc&offset");
				consultaInicial=url.replace(preferences.getString("offsetquery", "&offset"), "&orderby=precio;desc&offset");
				editor.putString("offsetquery", "&orderby=precio;desc&offset");
				editor.commit();
				Log.i("url mia", preferences.getString("offsetquery", "&offset"));
				Log.i("url mia", "url url "+consultaInicial);
				sb9 = consultaInicial;



				break;
			case 3:
				Log.i("VERIFICACION", "URL "+url+" replace this "+preferences.getString("offsetquery", "&offset")+" for this &orderby=colorexterior;asc&offset");

				consultaInicial=url.replace(preferences.getString("offsetquery", "&offset"), "&orderby=colorexterior;desc&offset");
				editor.putString("offsetquery", "&orderby=colorexterior;desc&offset");
				editor.commit();
				Log.i("url mia", preferences.getString("offsetquery", "&offset"));
				Log.i("url mia", "url url "+consultaInicial);
				sb9 = consultaInicial;



				break;
			case 4:
				Log.i("VERIFICACION", "URL "+url+" replace this "+preferences.getString("offsetquery", "&offset")+" for this &orderby=modelo;asc&offset");
				consultaInicial=url.replace(preferences.getString("offsetquery", "&offset"), "&orderby=modelo;desc&offset");
				editor.putString("offsetquery", "&orderby=modelo;desc&offset");
				editor.commit();
				Log.i("url mia", preferences.getString("offsetquery", "&offset"));
				Log.i("url mia", "url url "+consultaInicial);
				sb9 = consultaInicial;



				break;
			case 5:
				Log.i("VERIFICACION", "URL "+url+" replace this "+preferences.getString("offsetquery", "&offset")+" for this &orderby=tipotransmision;asc&offset");
				consultaInicial=url.replace(preferences.getString("offsetquery", "&offset"), "&orderby=tipotransmision;desc&offset");
				editor.putString("offsetquery", "&orderby=tipotransmision;desc&offset");
				editor.commit();
				Log.i("url mia", preferences.getString("offsetquery", "&offset"));
				Log.i("url mia", "url url "+consultaInicial);
				sb9 = consultaInicial;



				break;
			case 6:
				Log.i("VERIFICACION", "URL "+url+" replace this "+preferences.getString("offsetquery", "&offset")+" for this &orderby=kilometraje;asc&offset");
				consultaInicial=url.replace(preferences.getString("offsetquery", "&offset"), "&orderby=kilometraje;desc&offset");
				editor.putString("offsetquery", "&orderby=kilometraje;desc&offset");
				editor.commit();
				Log.i("url mia", preferences.getString("offsetquery", "&offset"));
				Log.i("url mia", "url url "+consultaInicial);
				sb9 = consultaInicial;


				break;

			default:
				Log.i("VERIFICACION", "URL "+url+" replace this "+preferences.getString("offsetquery", "&offset")+" for this &offset");
				consultaInicial=url.replace(preferences.getString("offsetquery", "&offset"), "&offset");
				editor.putString("offsetquery", "&offset");
				editor.commit();
				Log.i("url mia", preferences.getString("offsetquery", "&offset"));
				Log.i("url mia", "url url "+consultaInicial);
				sb9 = consultaInicial;



				break;
			}
			editor.commit();
		}else{
			consultaInicial=url;
			sb9 = consultaInicial;

			Log.i("url mia", "NINGUNA");

		}

		//		*****
		//        Log.i("url mia", "ordenar "+consulta);
		//        SharedPreferences preferencias = getSharedPreferences("Carro", Context.MODE_PRIVATE);
		//        SharedPreferences.Editor ed = preferencias.edit();
		//        ed.putString("urlconsulta", ""+consulta);
		//        ed.commit();


		URI myURI = null;
		try {
			myURI = new URI(consultaInicial);
		} catch (URISyntaxException e) {
			// Deal with it
		}
		HttpClient httpClient = new DefaultHttpClient();
		HttpGet getMethod = new HttpGet(myURI);
		HttpResponse webServerResponse = null;
		try {
			webServerResponse = httpClient.execute(getMethod);
		} catch (ClientProtocolException e) {
			// Deal with it
		} catch (IOException e) {
			// Deal with it
		}
		HttpEntity httpEntity = webServerResponse.getEntity();

		if (httpEntity != null) {
			try {
				is = httpEntity.getContent();
				BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
				StringBuilder sb = new StringBuilder();
				String line = null;
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				is.close();
				result=sb.toString();
				Log.i("TAG", result);

			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}



	}
	//	public boolean isOnline() {
	//	    ConnectivityManager cm =
	//	        (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
	//	    NetworkInfo netInfo = cm.getActiveNetworkInfo();
	//	    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
	//	        return true;
	//	    }
	//	    return false;
	//	}


	public boolean isNetwork(){
		//CHECA LA CONEXION A INTERNET
		NetworkInfo networkInfo = ((ConnectivityManager) getApplicationContext()
				.getSystemService(Context.CONNECTIVITY_SERVICE))
				.getActiveNetworkInfo();

		if(networkInfo == null || !networkInfo.isConnected()) {
			return false;
		}
		return true;
	}
}
















